package Threads.ReentrantLock.abcabcabc;


import java.util.concurrent.locks.LockSupport;

public class park_unpark {

    public static void main(String[] args) {
        Thread t1 = new Thread(() -> {
            Sync.print("a");
        });
        Thread t2 = new Thread(() -> {
            Sync.print("b");
        });
        Thread t3 = new Thread(() -> {
            Sync.print("c");
        });

        Thread[] threads=new Thread[]{t1,t2,t3};
        new Sync(5,threads).start();
    }

    static class Sync{
        private static int loopCount;

        private static Thread[] threads;

        public Sync(int loopCount,Thread[] threads){
            this.loopCount=loopCount;
            this.threads=threads;
        }

        public static void print(String str){
            for (int i=0;i<loopCount;i++){
                LockSupport.park();
                System.out.println(str);
                LockSupport.unpark(nextThread());
            }
        }

        public static Thread nextThread(){
            Thread current = Thread.currentThread();
            int index = 0;
            for (int i = 0; i < threads.length; i++) {
                if(threads[i] == current) {
                    index = i;
                    break;
                }
            }
            if(index < threads.length - 1) {
                return threads[index+1];
            } else {
                return threads[0];
            }
        }

        public void start() {
            for (Thread thread : threads) {
                thread.start();
            }
            LockSupport.unpark(threads[0]);
        }
    }
}
